<template>
  <div class="view-list-page">
    <van-tabs v-model="active" sticky swipeable line-width="20px" line-height="4px" @rendered="onRendered">
      <van-tab title="最新">
        <view-list :viewList="newList"></view-list>
      </van-tab>
      <van-tab title="精选">
        <view-list :viewList="selectList"></view-list>
      </van-tab>
    </van-tabs>
    <div class="text-center">
      <van-loading v-show="loading" type="spinner" size="16px">加载中...</van-loading>
    </div>
  </div>
</template>

<script>
import { Tab, Tabs, Loading } from 'vant';
import { pageViewApp } from '../../api/view';
import ViewList from './components/ViewList';

export default {
  components: {
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Loading.name]: Loading,
    ViewList
  },

  data() {
    return {
      active: 0,
      page: 1,
      size: 10,
      newList: [],
      selectList: [],
      loading: false
    }
  },

  mounted() {
    this.$setTitle('观点');
    this.$bus.$on('reachBottom', this.reachBottom.bind(this));
    this.$bus.$on('onPullDownRefresh', () => {
      setTimeout(() => {
        this.page = 1;
        this.pageViewApp().then(() => {
          this.$bus.$emit('stopPullDownRefresh');
        });
      }, 500)
    });
  },

  beforeDestroy() {
    this.$bus.$off('reachBottom');
  },

  methods: {
    async pageViewApp() {
      try {
        this.loading = true;
        const data = await pageViewApp({
          offset: 0,
          size: this.size,
          type: this.active === 0 ? 1 : 6
        });
        this.active === 0 ?
          this.newList = data.list
          :
          this.selectList = data.list;
      } catch (error) {
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    async reachBottom() {
      try {
        this.loading = true;
        ++this.page;
        const data = await pageViewApp({
          offset: (this.page - 1) * this.size,
          size: this.size,
          type: this.active === 0 ? 1 : 6
        });
        this.active === 0 ?
          this.newList = this.newList.concat(data.list)
          :
          this.selectList = this.selectList.concat(data.list)
      } catch (error) {
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    onRendered(name, title) {
      this.pageViewApp();
    }

  }
}
</script>

<style lang="less">
.view-list-page {
  .new-view-list {
    margin-top: 10px;
  }
  .van-tab__text {
    font-size: 16px;
  }
}
</style>
